const router = require('koa-router')()
const fs = require('fs');
const path = require('path');
router.get('/image', async (ctx) => {
  let wjj={};
  fs.readdir('routes/uploads', (err, files) => {
    if (err) throw err;
    console.log(files);
    wjj = files;
    console.log(wjj);
  });
    ctx.body = wjj;
    console.log(ctx.body);
  });
  
  router.get('/files', async (ctx) => {
    const page = ctx.request.query.page;
    console.log(page);
    let num = 5*(page-1);
    let files = []
    try {
      const allfiles = await getFiles('routes/uploads'); // 获取目录下文件列表
      for (let index = 0; index < 5; index++) {
        if(allfiles[num])
        files.push(allfiles[num])
        num++
      }
      console.log(files);
      ctx.body = files;
    } catch (err) {
      ctx.throw(500, err);
    }
  });
  router.delete('/delete-file', async (ctx) => {
    const fileName = ctx.request.query.fileName
    try {
      await fs.promises.unlink(fileName)
      ctx.body = 'File deleted successfully'
    } catch (error) {
      console.log(error)
      ctx.status = 500
      ctx.body = error.message
    }
  })
  // 实现getFiles函数，使用fs模块遍历目录并返回文件列表
async function getFiles(dirPath) {
  const files = [];
  const dir = await fs.promises.opendir(dirPath);
  for await (const dirent of dir) {
    const urls = `${dirent.name}`
    const filepath = `${dirPath}/${dirent.name}`;
    const stats = await fs.promises.stat(filepath);
    const file = {
      path: urls,
      size: stats.size,
      type: getFileType(filepath)
    };
    files.push(file);0

  }
  return files;
}
// 获取文件类型
function getFileType(filepath) {
  const ext = filepath.split('.').pop().toLowerCase();
  switch (ext) {
    case 'jpg':
      return 'jpg';
    case 'jpeg':
      return 'jpeg';
    case 'png':
      return 'png';
    default:
      return 'file';
  }
}
23
module.exports = router
